/**
 * Created by user on 2018/11/19.
 */

import { setAuthority } from '@/custom/authority'
import { routerRedux } from 'dva/router'
import { login } from '@/services/api'

export default {

  namespace: 'login',

  state: {},

  subscriptions: {},

  effects: {
    *login({ payload }, { put, call }) {
      const response = yield call(login, payload)
      if (response instanceof Error) {
        return
      }
      console.log('1', response)
      yield put({
        type: 'changeLoginStatus',
        payload: { ...response }
      })
      yield put({
        type: 'global/changeUser',
        payload: { ...response }
      })
      // setAuthority()
      yield put(routerRedux.push({
        pathname: '/about'
      }))
    },
    *logout({}, { put }) {
      yield put(routerRedux.push('/login'))
    }
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      console.log('111', payload)
      const { user, token } = payload
      console.log('2', user, token)
      let o = {
        role: user.role.name,
        browser: window.navigator.userAgent.toLowerCase(),
        token: token
      }
      setAuthority(o)
      return { ...state }
    }
  }

};
